package com.webcash.CNBoard.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webcash.CNBoard.Model.CreateWork;
import com.webcash.CNBoard.Model.Document;
import com.webcash.CNBoard.Model.Employee;
import com.webcash.CNBoard.Model.Project;
import com.webcash.CNBoard.Model.ProjectFile;
import com.webcash.CNBoard.Model.Work;
import com.webcash.CNBoard.Model.WorkDocFileTracer;
import com.webcash.CNBoard.Model.WorkInfoInProject;
import com.webcash.CNBoard.Model.WorkSearch;
import com.webcash.CNBoard.Model.WorkTracer;
import com.webcash.CNBoard.Repository.EmployeeRepository;
import com.webcash.CNBoard.Repository.HistoryRepository;
import com.webcash.CNBoard.Repository.ProjectRepository;
import com.webcash.CNBoard.Repository.WorkDocFileTracerRepository;
import com.webcash.CNBoard.Repository.WorkRepository;
import com.webcash.CNBoard.Repository.WorkTracerRepository;

@Service
public class ProjectServiceImpl implements ProjectService {

	@Autowired
	ProjectRepository projectRepository;

	@Autowired
	WorkRepository workRepository;
	@Autowired
	EmployeeRepository employeeRepository;
	@Autowired
	WorkTracerRepository workTracerRepository;
	@Autowired
	WorkDocFileTracerRepository workDocFileTracerRepository;
	@Autowired
	HistoryRepository historyRepository;

	public List<Work> getNewAllWorksById(String id) {
		return workRepository.selectNewAllWorksById(id);
	}

	public List<Project> getProjectListById(String id) {
		return projectRepository.selectProjectListById(id);
	}

	public List<Work> getWorkListByProjectNo(int projectNo, int pageNum) {

		return workRepository.selectWorkListByProjectNo(projectNo, pageNum);
	}


	public List<Work> getWorkListByProjectNo(int projectNo) {
		return workRepository.selectWorkListByProjectNo(projectNo);
	}

	public WorkInfoInProject getWorkListInfoByProjectNo(int projectNo) {
		List<Work> workList = workRepository.selectWorkListByProjectNo(projectNo);

		int progressWork = 0, newWork = 0, 
				completeWork = 0, rejectWork = 0,
				newFunction = 0, defect = 0;

		for(Work work : workList){

			if(work.getWorkType().equals("새기능"))
				newFunction++;
			if(work.getWorkType().equals("결함"))
				defect++;

			if(work.getWorkState().equals("신규"))
				newWork++;
			if(work.getWorkState().equals("진행"))
				progressWork++;
			if(work.getWorkState().equals("완료"))
				completeWork++;
			if(work.getWorkState().equals("거절")){
				rejectWork++;
			}
		}

		WorkInfoInProject workInfo = new WorkInfoInProject();

		workInfo.setNewWork(newWork);
		workInfo.setProgressWork(progressWork);
		workInfo.setCompleteWork(completeWork);
		workInfo.setRejectWork(rejectWork);
		workInfo.setTotalWork(workList.size());
		workInfo.setNewFunction(newFunction);
		workInfo.setDefect(defect);


		return workInfo;
	}

	public Project getProjectByProjectNo(int projectNo) {
		return projectRepository.selectProjectByProjectNo(projectNo);
	}

	public List<Work> getProgressWorkListById(String id) {

		return workRepository.selectProgressAllWorkListById(id);
	}

	public String addCreateWorkByWorkAndProjectNo(CreateWork createWork,
			int projectNo, int docNo, int fileNo) {
		Work work = new Work();

		work.setWorkType(createWork.getWorkType());
		work.setWorkPriority(createWork.getWorkPriority());
		work.setId(createWork.getId());
		work.setProjectNo(projectNo);
		work.setWorkProgress(createWork.getWorkProgress());
		work.setCoWorkers(createWork.getCoWorkers());
		Employee emp = employeeRepository.selectEmployeeById(createWork.getId());
		Project project = projectRepository.selectProjectByProjectNo(projectNo);

		////////
		String member = project.getProjectMember();


		if(emp == null){
			return "fail_id";
		}
		if(!member.contains(createWork.getId())){
			return "fail_id_project";
		}
		if(project == null){
			return "fail_project";
		}
		if(createWork.getWorkTitle().equals("")){
			return "fail_title_blank";
		}

		if (createWork.getStartDate() == null
				|| createWork.getStartDate().equals("")) {
			work.setWorkStartTime(new Date());
		}else{
			String value = createWork.getStartDate();
			String[] yyyymmdd = value.split("-");
			System.out.println(Integer.parseInt(yyyymmdd[1]));
			Date date = new Date();
			date.setYear(Integer.parseInt(yyyymmdd[0]) - 1900);
			date.setMonth(Integer.parseInt(yyyymmdd[1]) - 1);
			date.setDate(Integer.parseInt(yyyymmdd[2]));
			System.out.println(date);
			work.setWorkStartTime(date);
		}

		if (createWork.getDeadDate() == null
				|| createWork.getDeadDate().equals("")) {
			work.setWorkDeadTime(new Date());
		}else{
			String value = createWork.getDeadDate();
			String[] yyyymmdd = value.split("-");
			Date date = new Date();
			date.setYear(Integer.parseInt(yyyymmdd[0]) - 1900);
			date.setMonth(Integer.parseInt(yyyymmdd[1]) - 1);
			date.setDate(Integer.parseInt(yyyymmdd[2]));
			work.setWorkDeadTime(date);
		}


		work.setWorkState(createWork.getWorkState());
		work.setWorkTitle(createWork.getWorkTitle());
		work.setWorkExplanation(createWork.getWorkExplanation());
		workRepository.insertIntoWork(work);

		if(createWork.getUpperWorkNo() != 0){ //일감 연관 추가
			WorkTracer tracer = new WorkTracer();
			tracer.setUpperWorkNo(createWork.getUpperWorkNo());
			tracer.setUpperProjectNo(work.getProjectNo());
			tracer.setDownerProjectNo(work.getProjectNo());
			tracer.setDownerWorkNo(workRepository.selectLastWorkNo());
			tracer.setRelationType("상위일감");
			workTracerRepository.insertWorkTracer(tracer);
		}
		
		if(fileNo != 0 || docNo != 0){ // 파일 및 문서 연관 추가
			WorkDocFileTracer tracer = new WorkDocFileTracer();
			tracer.setProjectNo(work.getProjectNo());
			tracer.setWorkNo(workRepository.selectLastWorkNo());
			tracer.setDocNo(docNo);
			tracer.setFileNo(fileNo);
			tracer.setDocType("doc");
			tracer.setFileType("file");
			workDocFileTracerRepository.insertWorkDocFileTracer(tracer);
		}
		
		int createWorkNo = 1;
		historyRepository.addHistoryByProjectNoAndWhereNoAndJobNo(projectNo, createWorkNo, workRepository.selectLastWorkNo());
		
		
		return "success";

	}



	public String modifyCreateWorkByWorkAndProjectNo(CreateWork createWork,
			int projectNo, int workNo, int relationNo, int relationNo2, int docNo, int fileNo) {
		Work work = new Work();
		work.setWorkNo(workNo);
		work.setWorkType(createWork.getWorkType());
		work.setWorkPriority(createWork.getWorkPriority());
		work.setId(createWork.getId());
		work.setProjectNo(projectNo);
		work.setWorkProgress(createWork.getWorkProgress());
		work.setCoWorkers(createWork.getCoWorkers());

		Employee emp = employeeRepository.selectEmployeeById(createWork.getId());
		Project project = projectRepository.selectProjectByProjectNo(projectNo);

		String member = project.getProjectMember();


		if(emp == null){
			return "fail_id";
		}
		if(!member.contains(createWork.getId())){
			return "fail_id_project";
		}
		if(project == null){
			return "fail_project";
		}
		if(createWork.getWorkTitle().equals("")){
			return "fail_title_blank";
		}
		if (createWork.getStartDate() == null
				|| createWork.getStartDate().equals("")) {
			work.setWorkStartTime(new Date());
		}else{
			String value = createWork.getStartDate();
			String[] yyyymmdd = value.split("-");
			Date date = new Date();
			date.setYear(Integer.parseInt(yyyymmdd[0]) - 1900);
			date.setMonth(Integer.parseInt(yyyymmdd[1]) - 1);
			date.setDate(Integer.parseInt(yyyymmdd[2]));
			work.setWorkStartTime(date);
		}

		if (createWork.getDeadDate() == null
				|| createWork.getDeadDate().equals("")) {
			work.setWorkDeadTime(new Date());
		}else{
			String value = createWork.getDeadDate();
			String[] yyyymmdd = value.split("-");
			Date date = new Date();
			date.setYear(Integer.parseInt(yyyymmdd[0]) - 1900);
			date.setMonth(Integer.parseInt(yyyymmdd[1]) - 1);
			date.setDate(Integer.parseInt(yyyymmdd[2]));
			work.setWorkDeadTime(date);
		}

		work.setWorkState(createWork.getWorkState());
		work.setWorkTitle(createWork.getWorkTitle());
		work.setWorkExplanation(createWork.getWorkExplanation());
		work.setUpperWorks(createWork.getUpperWorkNo());
		workRepository.updateSetWork(work);



		if(createWork.getUpperWorkNo() != 0){ //일감 연관 추가
			if(relationNo != 0){
				WorkTracer tracer = workTracerRepository.getWorkTracerByRelationNo(relationNo);
				tracer.setUpperWorkNo(createWork.getUpperWorkNo());
				tracer.setUpperProjectNo(work.getProjectNo());
				workTracerRepository.modifyWorkTracer(tracer);
			}else{
				WorkTracer tracer = new WorkTracer();
				tracer.setUpperWorkNo(createWork.getUpperWorkNo());
				tracer.setUpperProjectNo(work.getProjectNo());
				tracer.setDownerProjectNo(work.getProjectNo());
				tracer.setDownerWorkNo(workNo);
				tracer.setRelationType("상위일감");
				workTracerRepository.insertWorkTracer(tracer);
			}
		}else{
			if(relationNo != 0){
				workTracerRepository.deleteWorkTracerByRelationNo(relationNo);
			}
		}
		
		if(fileNo != 0 || docNo != 0){ // 파일 및 문서 연관 추가
			if(relationNo2 != 0){
				WorkDocFileTracer tracer = workDocFileTracerRepository.selectWorkDocFileTracerByRelationNo(relationNo2);
				tracer.setDocNo(docNo);
				tracer.setFileNo(fileNo);
				workDocFileTracerRepository.updateWorkDocFileTracer(tracer);
			}else{
				WorkDocFileTracer tracer = new WorkDocFileTracer();
				tracer.setProjectNo(work.getProjectNo());
				tracer.setWorkNo(workRepository.selectLastWorkNo());
				tracer.setDocNo(docNo);
				tracer.setFileNo(fileNo);
				tracer.setDocType("doc");
				tracer.setFileType("file");
				workDocFileTracerRepository.insertWorkDocFileTracer(tracer);
			}
		}else{
			if(relationNo2 != 0){
				workDocFileTracerRepository.deleteWorkDocFileTracerByRelationNo(relationNo2);
			}
		}
		
		
		return "success";
	}

	public List<Employee> getMemberByProjectNo(int projectNo) {
		Project project = projectRepository.selectProjectByProjectNo(projectNo);
		String projectMember = project.getProjectMember();

		String[] members = projectMember.split(",");

		List<Employee> empList = new ArrayList<Employee>();

		for(String member : members){
			empList.add(employeeRepository.selectEmployeeById(member));
		}

		return empList;
	}

	public Work getWorkByWorkNo(int workNo) {
		return workRepository.selectWorkByWorkNo(workNo);
	}

	public List<Work> getAllWorkListById(String id) {
		return workRepository.selectAllWorkListById(id);
	}

	public List<Document> getDocumentListByProjectNo(int projectNo) {
		return projectRepository.selectDocumentListByProjectNo(projectNo);
	}

	public void addDocumentByDoc(Document doc) {
		projectRepository.insertDocumentByDoc(doc);
		int documentNo = 2;
		historyRepository.addHistoryByProjectNoAndWhereNoAndJobNo(doc.getProjectNo(), documentNo, projectRepository.selectLastDocNo());

	}

	public WorkTracer getWorkTracerByDownerWorkNo(int workNo) {
		return workTracerRepository.selectWorkTracerByDownerWorkNo(workNo);
	}

	public Work getUpperWorkByDownerWorkNo(int workNo) {
		WorkTracer workTracer = workTracerRepository.selectWorkTracerByDownerWorkNo(workNo);
		if(workTracer == null)
			return null;
		else
			return workRepository.selectWorkByWorkNo(workTracer.getUpperWorkNo());

	}

	public int getWorkListCountByProjectNo(int projectNo) {

		return workRepository.selectWorkListCountByProjectNo(projectNo);
	}

	public int getWorkListCountByProjectNoAndWorkSearch(int projectNo,
			WorkSearch search) {
		return workRepository.selectWorkListCountByProjectNoAndWorkSearch(projectNo, search);
	}

	public List<Work> getWorkListByProjectNoAndWorkSearch(int projectNo,
			WorkSearch search, int pageNum) {

		return workRepository.selectWorkListByProjectNoAndWorkSearch(projectNo, search,pageNum);
	}

	public List<Work> getDownerWorkListByProjectNoAndWorkNo(int projectNo,
			int workNo) {
		return workTracerRepository.selectDownerWorkListByProjectNoAndWorkNo(projectNo, workNo);
	}

	public void addWorkWithUpperWork(int workNo, int projectNo, int upperWorkNo) {
		workTracerRepository.insertWorkTracerWithUpperwork(workNo, projectNo, upperWorkNo);
	}

	public WorkDocFileTracer getWorkDocFileTracerByWorkNo(int workNo) {
		return workDocFileTracerRepository.selectWorkDocFileTracerByWorkNo(workNo);
	}

	public Document getDocumentByDocNo(int docNo) {
		return projectRepository.selectDocumentByDocNo(docNo);
	}
	
	public List<Work> getWorkTracerListByProjectNo(int projectNo) {
		System.out.println("projectNo"+projectNo);
		List<Work> workList =  workTracerRepository.getWorkListByProjectNo(projectNo);
		/*System.out.println("gg" + worklist);
		List<Work> workArray = new ArrayList<Work>();
		for(int i=0;i<worklist.size();i++){
			boolean exist = false;
			for(int j=0;j<worklist.size();j++){
				if(worklist.get(i).getUpperWorkNo()==worklist.get(j).getDownerWorkNo()){
					exist = true;
				}
			}

			if(!exist){
				workArray.add(worklist.get(i));
				sortWork(worklist, worklist.get(i), workArray);
			}
		}

		checkListDuplicate(workArray);
		return workArray;*/
		System.out.println(workList);
		return workList;
	}

	public List<Work> sortWork(List<Work> worklist, Work work, List<Work> workArray){
		if(work.getDownerWorkNo()==0){
			return workArray;
		}
		for(int i=0;i<worklist.size();i++){
			if(work.getDownerWorkNo()==worklist.get(i).getUpperWorkNo()){
				workArray.add(worklist.get(i));
				sortWork(worklist, worklist.get(i), workArray);
			}
		}
		return workArray;

	}

	public List<Work> checkListDuplicate(List<Work> arraylist){
		int[] arrayNumber = new int[10000];
		ArrayList<Integer> list = new ArrayList<Integer>();
		int count=0;

		for(int i=0;i<arraylist.size()-1;i++){
			for(int j=i+1;j<arraylist.size();j++){
				if(arraylist.get(i).getWorkNo() == arraylist.get(j).getWorkNo()){
					arrayNumber[count] = j;
					count++;
				}
			}
		}

		for(int i=0;i<count;i++){
			if(!list.contains(arrayNumber[i])){
				list.add(arrayNumber[i]);
			}
		}
		Collections.sort(list);
		for(int i=list.size()-1;i>=0;i--){
			arraylist.remove((int)list.get(i));
		}
		return arraylist;
	}

	public void removeDocumentByDocNo(int docNo) {
		
		int docWhereNo = 2;
		historyRepository.deleteHistoryByWhereNoAndJobNo(docWhereNo	, docNo);
		
		projectRepository.deleteDocumentByDocNo(docNo);
	}

	public void removeWorkByWorkNo(int workNo) {
		int workWhereNo = 1;
		historyRepository.deleteHistoryByWhereNoAndJobNo(workWhereNo, workNo);
		workTracerRepository.deleteWorkTracerByWorkNo(workNo);
		workDocFileTracerRepository.deleteWorkDocFileTracerByWorkNo(workNo);
		workRepository.deleteWorkByWorkNo(workNo);
	}

	public void addWorkWithDocument(int workNo, int projectNo, int docNo) {
		WorkDocFileTracer workDocFileTracer = workDocFileTracerRepository.selectWorkDocFileTracerByWorkNo(workNo);
		if(workDocFileTracer != null){
			workDocFileTracer.setDocNo(docNo);
			workDocFileTracerRepository.updateWorkDocFileTracer(workDocFileTracer);
		}else{
			workDocFileTracer = new WorkDocFileTracer();
			workDocFileTracer.setProjectNo(projectNo);
			workDocFileTracer.setWorkNo(workNo);
			workDocFileTracer.setDocNo(docNo);
			workDocFileTracerRepository.insertWorkDocFileTracer(workDocFileTracer);
			
		}
	}

	public void addWorkWithFile(int workNo, int projectNo, int fileNo) {
		WorkDocFileTracer workDocFileTracer = workDocFileTracerRepository.selectWorkDocFileTracerByWorkNo(workNo);
		if(workDocFileTracer != null){
			workDocFileTracer.setFileNo(fileNo);
			workDocFileTracerRepository.updateWorkDocFileTracer(workDocFileTracer);
		}else{
			workDocFileTracer = new WorkDocFileTracer();
			workDocFileTracer.setProjectNo(projectNo);
			workDocFileTracer.setWorkNo(workNo);
			workDocFileTracer.setFileNo(fileNo);
			workDocFileTracerRepository.insertWorkDocFileTracer(workDocFileTracer);
		}
		
	}

	public List<Work> getWorkListByProjectNoAndId(int projectNo, String id) {
		return workRepository.selectWorkListByProjectNoAndEmpNo(projectNo, id);
		
	}
	
	
	
	
}
